﻿function $sp(id, args) {
    var $d = document, that = this;
    function make(t, p, a, c) {
        var e = $d.createElement(t);
        if (a) { for (var i in a) e.setAttribute(i, a[i]); }
        if (navigator && navigator.userAgent) {
            var g = navigator.userAgent;
            if (g.indexOf('MSIE 6.0') > 0 || g.indexOf('MSIE 7.0') > 0)
                e = $d.createElement(e.outerHTML.replace('\r\n', ''));
        }
        if (c) e.innerHTML = c;
        if (p) p.appendChild(e);
        return e;
    }    
    this.id = id;
    var e = $d.getElementById(id);
    if (!e) return;
    var p = {
        pageIndex: 1,
        pageCount: 0,
        maxRange: 10,
        prev: 'Prev',
        next: 'Next',
        callback: null,
        requestUrl: '#',
        style: 'smithpaginator'
    };
    for (var i in p) { if (args[i]) p[i] = args[i]; }    
    function ml(t, i) {
        var a = make('a', that.ctrl, { 'href': p.requestUrl.replace('@pid', i) }, t);
        if (p.callback) a.onclick = function () { return p.callback(that, i); }
        return a;
    }
    function rd() {
        if (that.ctrl) {
            e.removeChild(that.ctrl);
            that.ctrl = null;
        }
        that.ctrl = make('div', e, { 'class': p.style });
        if (p.prev && p.pageIndex > 1) ml(p.prev, p.pageIndex - 1);
        if (p.pageIndex >= 1 && p.pageIndex <= p.pageCount && p.maxRange > 0) {
            var f = 0, t = 0, d = '&middot;&middot;&middot;';
            if (p.pageCount < p.maxRange) { f = 1; t = p.pageCount; }
            else if (p.pageIndex <= Math.ceil(p.maxRange / 2)) { f = 1; t = p.maxRange; }
            else if (p.pageIndex >= p.pageCount - Math.floor(p.maxRange / 2)) { f = p.pageCount - p.maxRange + 1; t = p.pageCount; }
            else { f = p.pageIndex - Math.ceil(p.maxRange / 2) + 1; t = p.pageIndex + Math.floor(p.maxRange / 2); }
            if (f > 1) {
                ml(1, 1);
                make('span', that.ctrl, null, d);
            }
            for (var i = f; i <= t; i++) {
                if (i == p.pageIndex) {
                    var a = make('a', that.ctrl, { 'class': 'current', 'href': '#' }, i);
                    a.onclick = function () { return false; }
                }
                else ml(i, i);
            }
            if (t < p.pageCount) {
                make('span', that.ctrl, null, d);
                ml(p.pageCount, p.pageCount);
            }
        }
        if (p.next && p.pageIndex < p.pageCount) ml(p.next, p.pageIndex + 1);
    }
    this.setPageIndex = function (i) { p.pageIndex = i; rd(); }
    rd();
}
$sp.getPageIndex = function (key) {
    var u = window.location.search,
        r = new RegExp(key + "=([^&?]*)", "ig");
    return ((u.match(r)) ? parseInt(u.match(r)[0].substr(key.length + 1)) : 1);
}
SmithPaginator = $sp;